<?php

class Admin_UsersController extends Zend_Controller_Action {

    /**
     * @var Nosql_Model_Users
     * 
     */
    private $userModel = null;

    public function init() {
        $this->view->sidebarMenu = 'users';
        $this->userModel = new Nosql_Model_Mysql_User();
        $this->view->userObj = Zend_Auth::getInstance()->getIdentity();
    }

    public function indexAction() {
        $page = $this->_getParam('page');
        $page = (isset($page)) ? $page : 1;

        if (!Nosql_Util_Validator::validateInt($page)) {
            throw new Exception('Valor invalido en los parametros');
        }

        $users = $this->userModel->listUsers($page);
        $this->view->users = $users['items'];
        if (count($this->view->users) == 0) {
            $this->view->attention = array('No se encontraron usuarios');
        } else {
            $this->view->paginator = $users['paginator'];
            $this->view->urlPagination = '/admin/users/index/';
        }
    }

    public function addAction() {
        $form = new Admin_Form_User();
        $form = $form->addUser();
        $errors = array();

        //Validate the form
        $request = $this->getRequest();
        if ($request->isPost()) {
            //valiate if theh form is valid
            if ($form->isValid($request->getPost())) {

                $formValues = $form->getValues();

                //validate the two passwords
                if ($formValues['user']['passwd'] != $formValues['user']['passwd2']) {
                    $errors[] = "Las contraseñas no coinciden";
                }

                //validate if the username doesn't exists
                if ($this->userModel->userExists($formValues['user']['username'])) {
                    $errors[] = 'El usuario que eligio ya esta tomado';
                }

                // if there are no errors then I can create the user
                if (count($errors) == 0) {

                    $data['username'] = $formValues['user']['username'];
                    $data['email'] = $formValues['user']['email'];
                    $data['passwd'] = $formValues['user']['passwd'];
                    $data['fullname'] = $formValues['user']['fullname'];
                    $data['role'] = $formValues['user']['role'];
                    if (isset($formValues['user']['website'])) {
                        $data['website'] = $formValues['user']['website'];
                    }

                    $response = $this->userModel->createUser($data);
                    if ($response['status'] > -1) {
                        $this->view->success = array("Usuario creado");
                        $this->_forward('index');
                        return;
                    } else {
                        $errors[] = $response['message'];
                    }
                }
            }
        }

        if (count($errors) > 0) {
            $this->view->errors = $errors;
        }

        $this->view->form = $form;
    }

    public function editAction() {
        $form = new Admin_Form_User();
        $errors = array();
        $continue = true;

        //Validate the form
        $request = $this->getRequest();

        //get the User Object
        $id = $request->getParam('user');
        if ($id == null || !is_numeric($id)) {
            $continue = false;
            $errors[] = "No selecciono ningun usuario";
        }

        $user = null;
        if ($continue) {
            $user = $this->userModel->getUserById($id);
            if (!$user) {
                $continue = false;
                $errors[] = 'Hubo un error al obtener el usuario';
            } else {
                $form = $form->editUser($user['userid']);
            }
        }

        if ($continue && $request->isPost()) {
            //valiate if theh form is valid
            if ($form->isValid($request->getPost())) {

                $formValues = $form->getValues();

                //validate the two passwords if the user entered two passwords
                $password = $formValues['user']['passwd'];
                if (strlen($password) > 0) {
                    if ($formValues['user']['passwd'] != $formValues['user']['passwd2']) {
                        $errors[] = "Las contraseñas no coinciden, para actualizarlas deben coincidir las 2";
                    }
                } else {
                    $password = null;
                }

                // if there are no errors then I can create the user
                if (count($errors) == 0) {

                    $data['email'] = $formValues['user']['email'];
                    $data['fullname'] = $formValues['user']['fullname'];
                    $data['role'] = $formValues['user']['role'];
                    if (isset($formValues['user']['website'])) {
                        $data['website'] = $formValues['user']['website'];
                    }
                    $data['passwd'] = $password;
                    $data['userid'] = $user['userid'];

                    $response = $this->userModel->updateUser($data);
                    if ($response['status'] > -1) {
                        $this->view->success = array("Usuario actualizado exitosamente");
                        $this->_forward('index');
                        return;
                    } else {
                        $errors[] = $response['message'];
                    }
                }
            }
        }

        if (count($errors) > 0) {
            $this->view->errors = $errors;
        }

        if ($continue) {
            //Populate the Form
            $data['username'] = $user['username'];
            $data['email'] = $user['email'];
            $data['passwd'] = $user['passwd'];
            $data['fullname'] = $user['fullname'];
            $data['role'] = $user['role'];
            $data['website'] = $user['website'];

            $form->populate($data);
            $this->view->form = $form;
        }

        if (!$continue) {
            $this->_forward('index');
        }
    }

    public function imageAction() {
        $form = new Admin_Form_User();
        $errors = array();
        $continue = true;

        //Validate the form
        $request = $this->getRequest();

        //get the User Object
        $id = $request->getParam('user');
        if ($id == null || !is_numeric($id)) {
            $continue = false;
            $errors[] = "No selecciono ningun usuario";
        }

        $user = null;
        if ($continue) {
            $user = $this->userModel->getUserById($id);
            if (!$user) {
                $continue = false;
                $errors[] = 'Hubo un error al obtener el usuario';
            } else {
                $form = $form->imageEdit($user['userid']);
                $this->view->username = $user['username'];
                $this->view->userId = $user['userid'];
            }
        }

        if ($continue && $request->isPost() && $form->isValid($request->getParams())) {

            if (!$form->imagen->receive()) {
                $errors = 'Error al recibir el archivo';
            }

            if ($form->imagen->isUploaded()) {
                $values = $form->getValues();
                $source = $form->imagen->getFileName();

                //to re-name the image, all you need to do is save it with a new name, instead of the name they uploaded it with. Normally, I use the primary key of the database row where I'm storing the name of the image. For example, if it's an image of Person 1, I call it 1.jpg. The important thing is that you make sure the image name will be unique in whatever directory you save it to.

                $new_image_name = $user['username'];

                //save image to database and filesystem here
                $destination = APPLICATION_PATH . '/../public/img/userimg/' . $new_image_name . '.png';


                /**
                 * RESIZE IMAGE
                 */
                require_once 'PHPThumb/ThumbLib.inc.php';
                $isResized = false;
                try {
                    $thumb = PhpThumbFactory::create($source);
                    $thumb->resize(125, 125);
                    $thumb->save($destination);
                    $isResized = true;
                } catch (Exception $e) {
                    // handle error here however you'd like
                }

                if ($isResized) {
                    $form->reset(); //only do this if it saved ok and you want to re-display the fresh empty form
                    $continue = true;
                } else {
                    $errors[] = 'Error al guardar la imagen ' . $source . ' path: ' . $path;
                    echo "No funciono";
                    exit;
                }
            }
        }

        if (count($errors) > 0) {
            $this->view->errors = $errors;
        }

        if ($continue) {
            $this->view->form = $form;
        }

        if (!$continue) {
            $this->_forward('index');
        }
    }

    public function deleteAction() {

        //get the User Object
        $success = array();
        $errors = array();
        $id = $this->getRequest()->getParam('user');
        if ($id == null || !is_numeric($id)) {
            $errors = array("No selecciono ningun usuario");
        } else {
            $response = $this->userModel->deleteUserById($id);
            if ($response['status'] > 0) {

                $success[] = $response['message'];
            } else {
                $errors[] = $response['message'];
            }
        }

        if (count($errors) > 0) {
            $this->view->errors = $errors;
        }
        if (count($success) > 0) {
            $this->view->success = $success;
        }

        $this->_forward('index');
        return;
    }

    public function searchAction() {
        $form = new Admin_Form_User();
        $errors = array();
        $success = array();
        $information = array();
        $continue = true;

        $page = $this->_getParam('page');
        $page = (isset($page)) ? $page : 1;

        if (!Nosql_Util_Validator::validateInt($page)) {
            throw new Exception('Valor invalido en los parametros');
        }


        $form = $form->searchUser();
        $request = $this->getRequest();
        if ($continue && $form->isValid($request->getParams())) {
            $formValues = $form->getValues();
            $query = $formValues['user']['q'];
            $field = $formValues['user']['field'];

            // NOW PREPARE THE VALUES TO DO THE SEARCH
            $useLiteral = false;
            switch ($field) {
                case 1:
                    $field = 'username';
                    $useLiteral = true;
                    break;
                case 2:
                    $field = 'email';
                    break;
                case 3:
                    $field = 'fullname';
                    $useLiteral = true;
                    break;
                case 4:
                    $field = 'role';
                    break;
                default:
                    $field = '';
                    break;
            }

            if (strlen($query) > 0) {
                $users = $this->userModel->searchUserByField($query, $field, $useLiteral, $page);
                if ($users['items']) {
                    $this->view->users = $users['items'];
                    $this->view->paginator = $users['paginator'];
                    $this->view->urlPagination = '/admin/users/search/q/' . $query . '/field/' . $formValues['user']['field'] . '/';
                } else {
                    $information[] = 'Usuarios no encontrados';
                }
            } else {
                $errors[] = 'Campo seleccionado es invalido';
            }
        }


        if (count($errors) > 0) {
            $this->view->errors = $errors;
        }
        if (count($success) > 0) {
            $this->view->success = $success;
        }
        if (count($information) > 0) {
            $this->view->information = $information;
        }
        $this->view->form = $form;
    }

}

